package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName AlbumReceiver
 * @description: TODO
 * @date 2023年12月04日
 * @version: 1.0
 */
@Component
public class AlbumReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    //  监听数据
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdate(ConsumerRecord<String,String> record){
        //  获取发送的数据内容
        String str = record.value();
        //  判断
        if (!StringUtils.isEmpty(str)){
            //  说明有数据.
            TrackStatMqVo trackStatMqVo = JSON.parseObject(str, TrackStatMqVo.class);
            //  获取到业务编号 去重？
            String businessNo = trackStatMqVo.getBusinessNo();
            //  保证消息幂等性.
            if (null != redisTemplate){
                try {
                    Boolean isExist = redisTemplate.opsForValue().setIfAbsent(businessNo, "ok",1, TimeUnit.DAYS);
                    if (isExist){
                        //  isExist = true; 说明的第一次消费.
                        //  调用方法.
                        trackInfoService.updateStat(trackStatMqVo.getAlbumId(),trackStatMqVo.getTrackId(),trackStatMqVo.getStatType(),trackStatMqVo.getCount());
                    }
                } catch (Exception e) {
                    this.redisTemplate.delete(businessNo);
                    throw new RuntimeException(e);
                }
                //  更新统计记录.track,album
            }

        }
    }
}
